package com.jessechanrui.template.common.template.auth.config.handler;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.jessechanrui.template.common.template.auth.common.AuthorizationSupport;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;

import java.util.List;

/**
 * @author chenrui
 * @version 1.0
 * @description CustomTenantLineHandler
 * @date 2025/7/18
 */
public class CustomTenantLineHandler implements TenantLineHandler {

    private String tenantId;

    private List<String> ignoreTables;

    public CustomTenantLineHandler(List<String> ignoreTables, String tenantId) {
        this.ignoreTables = ignoreTables;
        this.tenantId = tenantId;
    }

    // 指定租户 ID 对应的字段名
    @Override
    public String getTenantIdColumn() {
        return "tenant_id";
    }

    // 获取租户 ID 值
    @Override
    public Expression getTenantId() {
        // 默认为配置租户
        String currentTenantId = AuthorizationSupport.getCurrentTenantId();
        if(AuthorizationSupport.getCurrentTenantId() == null){
            currentTenantId = tenantId;
        }
        if (currentTenantId != null) {
            return new StringValue(currentTenantId);
        }
        return null;
    }

    // 过滤不需要进行租户过滤的表
    @Override
    public boolean ignoreTable(String tableName) {
        // 这里可以配置白名单表，例如系统表不需要进行租户过滤
        if(CollectionUtil.isNotEmpty(ignoreTables)){
            return ignoreTables.contains(tableName);
        }else{
            return false;
        }

    }
}
